#!/usr/bin/env python
# -*- coding:utf-8 -*-

from controller.wordbookController import WordbookController

import datetime
import math

from flask import current_app ,make_response ,jsonify,g
from sqlalchemy import or_
from werkzeug.security import generate_password_hash, check_password_hash

from app import db
from models.wordbook import Wordbook
from models.word_wordbook_append import WordWordbookAppend
from models.word import Word
from models.user import User
from utils import commons
from utils.generate_id import GenerateID
from utils.loggings import loggings
from utils.response_code import RET, error_map_EN
from utils.rsa_encryption_decryption import RSAEncryptionDecryption

class WordbookService(WordbookController):

    # 创建单词本
    @classmethod
    def create_wordbook(cls,user_id, wordbook_name):
        try:
            # 检查用户是否存在
            user = User.query.filter_by(user_id=user_id).first()
            if not user:
                return {'code': RET.PARAMERR, 'message': '用户不存在', 'data': None}

            # 检查同一用户的单词本名是否重复
            existing_wordbook = Wordbook.query.filter_by(user_id=user_id, wordbook_name=wordbook_name).first()
            if existing_wordbook:
                return {'code': RET.PARAMERR, 'message': '单词本名重复', 'data': None}

            wordbook_id = GenerateID.create_random_id()
            # 创建新的单词本
            new_wordbook = Wordbook(
                wordbook_id=wordbook_id,
                user_id=user_id,
                wordbook_name=wordbook_name,
                is_delete=0
            )
            db.session.add(new_wordbook)
            db.session.commit()
            return {'code': RET.OK, 'message': '成功创建单词本', 'data': {'wordbook_id': new_wordbook.wordbook_id}}
        except Exception as e:
            db.session.rollback()
            return {'code': RET.DBERR, 'message': f'数据库错误', 'data': None}
        finally:
            db.session.close()

    # 添加单词到单词本
    @classmethod
    def add_word_to_wordbook(cls, user_id, word_id, wordbook_id):
        try:
            # 检查用户是否存在
            user = User.query.filter_by(user_id=user_id).first()
            if not user:
                return {'code': RET.PARAMERR, 'message': '用户不存在', 'data': None}

            # 检查单词是否存在
            word = Word.query.filter_by(word_id=word_id).first()
            if not word:
                return {'code': RET.PARAMERR, 'message': '单词不存在', 'data': None}

            # 检查单词本是否存在
            wordbook = Wordbook.query.filter_by(wordbook_id=wordbook_id, user_id=user_id).first()
            if not wordbook:
                return {'code': RET.PARAMERR, 'message': '单词本不存在', 'data': None}

            # 检查单词是否已经存在于单词本中
            existing_entry = WordWordbookAppend.query.filter_by(word_id=word_id, wordbook_id=wordbook_id).first()
            if existing_entry:
                return {'code': RET.PARAMERR, 'message': '单词已经存在于单词本中', 'data': None}

            # 创建新的单词和单词本关联记录
            new_entry = WordWordbookAppend(
                wordbook_append_id=GenerateID.create_random_id(),
                word_id=word_id,
                wordbook_id=wordbook_id,
                user_id=user_id,
                is_delete=0
            )
            db.session.add(new_entry)
            db.session.commit()
            return {'code': RET.OK, 'message': '成功将单词加入单词本', 'data': None}
        except Exception as e:
            db.session.rollback()
            return {'code': RET.DBERR, 'message': f'数据库错误: {str(e)}', 'data': None}
        finally:
            db.session.close()

    # 获取单词本中的单词列表逆序或正序
    @classmethod
    def get_words_by_wordbook_id(cls, wordbook_id, reverse=False):
        try:
            # 获取单词本中的单词列表
            words = db.session.query(Word).join(WordWordbookAppend, Word.word_id == WordWordbookAppend.word_id).filter(
                WordWordbookAppend.wordbook_id == wordbook_id,
                WordWordbookAppend.is_delete == 0
            ).all()

            # 将单词对象转换为字典列表
            words_list = [{'word_name': word.word_name, 'word_paraphrase': word.word_paraphrase} for word in words]

            # 按单词顺序或逆序排序
            sorted_words = sorted(words_list, key=lambda x: x['word_name'], reverse=reverse)

            return {'code': RET.OK, 'message': '成功获取单词列表', 'data': sorted_words}
        # except Exception as e:
        #     return {'code': RET.DBERR, 'message': f'数据库错误: {str(e)}', 'data': None}
        finally:
            db.session.close()

    # 获取指定用户的单词本列表
    @classmethod
    def get_wordbooks_by_user_id(cls, user_id):
        try:
            # 获取指定用户的单词本列表
            wordbooks = Wordbook.query.filter_by(user_id=user_id, is_delete=0).all()

            # 将单词本对象转换为字典列表
            wordbooks_list = [
                {
                    'wordbook_id': wordbook.wordbook_id,
                    'wordbook_name': wordbook.wordbook_name,
                }
                for wordbook in wordbooks
            ]

            return {'code': RET.OK, 'message': '成功获取单词本列表', 'data': wordbooks_list}
        # except Exception as e:
        #     return {'code': RET.DBERR, 'message': f'数据库错误: {str(e)}', 'data': None}
        finally:
            db.session.close()
